<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="学科名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入学科名称" />
      </el-form-item>
      <el-form-item label="教育阶段" prop="level">
        <el-select v-model="form.level" placeholder="请选择教育阶段">
          <el-option :key="1" label="小学" :value="1" />
          <el-option :key="2" label="初中" :value="2" />
          <el-option :key="3" label="高中" :value="3" />
          <el-option :key="4" label="大学" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入描述" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getSubjectDetail as getSubject, addSubject, updateSubject } from '@/api/subject';

export default {
  name: 'SubjectEdit',
  data() {
    return {
      form: {
        id: undefined,
        name: '',
        level: undefined,
        description: ''
      },
      rules: {
        name: [{ required: true, message: '请输入学科名称', trigger: 'blur' }],
        level: [{ required: true, message: '请选择教育阶段', trigger: 'change' }]
      },
      loading: false,
      isEdit: false
    };
  },
  created() {
    if (this.$route.params && this.$route.params.id) {
      this.isEdit = true;
      this.fetchData(this.$route.params.id);
    }
  },
  methods: {
    fetchData(id) {
      this.loading = true;
      getSubject(id)
        .then(response => {
          this.form = response.data;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true;
          const request = this.isEdit ? updateSubject(this.form) : addSubject(this.form);
          request
            .then(() => {
              this.$message({
                message: this.isEdit ? '更新成功' : '创建成功',
                type: 'success'
              });
              this.loading = false;
              this.goBack();
            })
            .catch(() => {
              this.loading = false;
              this.$message({
                message: this.isEdit ? '更新失败' : '创建失败',
                type: 'error'
              });
            });
        }
      });
    },
    cancel() {
      this.goBack();
    },
    goBack() {
      this.$router.push('/subjects');
    }
  }
};
</script> 